package cn.yzj.openapi.dao.impl;

import cn.yzj.openapi.common.Common;
import cn.yzj.openapi.converter.SettingsConverter;
import cn.yzj.openapi.dao.base.ApiSettingsBaseDao;
import cn.yzj.openapi.dao.intf.ApiSettingsDao;
import cn.yzj.openapi.dto.SettingsDTO;
import cn.yzj.openapi.entity.ApiSettingsEntity;
import cn.yzj.openapi.enums.error.SettingsErrorEnums;
import cn.yzj.openapi.exception.OpenApiException;
import cn.yzj.openapi.mapper.ApiSettingsMapper;
import cn.yzj.openapi.utils.SettingsJsonUtils;
import cn.yzj.openapi.wrapper.ApiSettingsQuery;
import com.google.common.cache.Cache;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

/**
 * api 设置逻辑实现层
 *
 * @author gzkemays
 * @since 2022/03/30 17:18
 */
@Repository
public class ApiSettingsDaoImpl extends ApiSettingsBaseDao implements ApiSettingsDao {
  @Resource(name = "settingCache")
  Cache<String, Object> settingCache;

  @Resource ApiSettingsMapper settingsMapper;

  @Override
  public void update(ApiSettingsEntity entity) {
    int count = settingsMapper.count(query().where.id().eq(entity.getId()).end());
    if (count == 0) {
      throw OpenApiException.settingsException(SettingsErrorEnums.SETTINGS_ID_IS_NOT_FOUND);
    }
    entity.setSettings(entity.getSettings());
    settingCache.invalidateAll();
    settingsMapper.updateById(entity);
    resetSettingCache(ALL);
  }

  @Override
  public void insertSettings(SettingsDTO dto) {
    if (count(query().where.id().eq(dto.getId()).end()) > 0) {
      throw OpenApiException.settingsException(SettingsErrorEnums.SETTINGS_IS_EXISTED);
    }
    settingsMapper.save(SettingsConverter.INSTANCE.convertEntityByDTO(dto));
  }

  @Override
  public void resetSettingCache(Integer mode) {
    ApiSettingsEntity one =
        settingsMapper.findOne(
            new ApiSettingsQuery().selectAll().where.id().eq(Common.BEST_AUTH_POWER).end());
    int picMaxCount =
        Integer.parseInt(SettingsJsonUtils.getSettingsVal(one.getSettings(), PIC_MAX_COUNT));
    if (mode.equals(ALL)) {
      settingCache.put(IMG_COUNT_LIST_CACHE_KEY, generateNumberSet(1, picMaxCount));
    } else if (mode.equals(IMG)) {
      settingCache.put(IMG_COUNT_LIST_CACHE_KEY, generateNumberSet(1, picMaxCount));
    }
  }
}
